#include <iostream>
#include "GameServer.h"

//===========================================================================
void GameServer::PrintOut(
    EEvent             event,
    SOCKET             client,
    Message::Packet *  packet /* = NULL */
) {
    const char * message[ EE_COUNT ] = {
        "CONNECTED    from : %d\r\n",
        "DISCONNECTED from : %d\r\n",
        "ON READ      from : %d\r\n"
    };
    printf( message[ event ], client );

    if( EE_ON_READ == event )
        if( packet ) {
            const char * output = 
                "\tversion : %d\r\n"
                "\ttype    : %d\r\n"
                "\tuser    : %d\r\n"
                "\tpayload : %s\r\n";
            printf(
                output,
                packet->version,
                packet->type,
                packet->user,
                packet->payload
            );
        }
}

//===========================================================================
bool GameServer::OnConnected(
    SOCKET client
) {
    this->PrintOut( EE_CONNECTED, client );
    
    return true;
}

//===========================================================================
void GameServer::OnDisconnected(
    SOCKET client
) {
    this->PrintOut( EE_DISCONNECTED, client );
}
    
//===========================================================================
bool GameServer::OnRead(
          SOCKET client,
    const char *     data,
          unsigned   size,
          unsigned & processed
) {
    if( !data || !size )
        return false;
    
    processed = 0;
    while( true ) {
        Message::Packet packet;
        unsigned int parsed = Message::Parse(
            data,
            size,
            packet
        );

        if( !( parsed > 0 ) )
            break;

        this->PrintOut( EE_ON_READ, client, &packet );

        data      += parsed;
        size      -= parsed;
        processed += parsed;
    }    
    
    return true;
}

//===========================================================================
GameServer::GameServer( void ) {
}

//===========================================================================
GameServer::~GameServer( void ) {
}